package main

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

var sy sync.WaitGroup

func hello(i int) {
	defer sy.Done()
	fmt.Println("Hello Goroutine!", i)
}

//channel
//make(chan int,40)

var ch chan int

func test() {
	jobs := make(chan int, 100)
	res := make(chan int, 100)

	for w := 1; w <= 128; w++ {
		
	}
}


func main() {
	runtime.GOMAXPROCS(1)	//设置多少个os线程来执行go代码
	for i := 0; i < 10; i++ {
		go hello(i)
		sy.Add(1)
	}
	sy.Wait()

	ch1 := make(chan int)
	ch2 := make(chan int)
	go func() {
		for i := 0; i < 100; i++ {
			ch1 <- i
		}
		close(ch1)
	}()
	go func() {
		for  {
			i, ok := <- ch1
			if !ok {
				break
			}
			ch2 <- i * i
		}
		close(ch2)
	}()
	for i := range ch2{
		fmt.Println(i)
	}
	chtest1 := make(chan int)
	chtest2 := make(chan int)
	go counter(chtest1)
	go squarer(chtest2, chtest1)
	printer(chtest2)
	//select 多路复用
	jobs := make(chan int, 100)
	results := make(chan int, 100)
	for w := 1; w <= 3; w++ {
		go worker(w, jobs, results)
	}
	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)
	for a := 1; a <= 5; a++ {
		<- results
	}

}


//worker pool
func worker(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Printf("worker %d, start job:%d\n", id, j)
		time.Sleep(time.Second)
		fmt.Printf("worker %d, start job:%d\n", id, j)
		results <- j * 2
	}
}

//单向通道
func counter(out chan<- int) {
	fmt.Println("counter")
	for i := 0; i < 10; i++{
		out <- i
	}
	close(out)
}
func squarer(out chan<- int, in <-chan int) {
	fmt.Println("squarer")
	for i := range in{
		out <- i * i
	}
	close(out)
}
func printer(in <-chan int) {
	fmt.Println("printer")
	for i := range in{
		fmt.Println(i)
	}
}